package net.majodali.glasshouse.filesystem;

import java.io.File;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

import net.majodali.glasshouse.AbstractProject;
import net.majodali.glasshouse.Resource;
import net.majodali.util.NestedIterator;

public class FileSystemProject extends AbstractProject {
	public Map<String, File> projectRoots = new TreeMap<String, File>(new Comparator<String>(){
		public int compare(String s1, String s2) {
			return s1 == null ? s2 == null ? 0 : -1 : s2 == null ? 1 : s1.compareTo(s2);
		}
	});
	
	public FileSystemProject() {
	}

	public FileSystemProject(String path) {
		root(null, path);
	}

	protected FileResource createResource(String path) {
		if (path.charAt(0) != '/')
			path = "/" + path;
		int end = path.indexOf('/', 1);
		String rootName = end == -1 ? path.substring(1) : path.substring(1, end);
		
		File root = projectRoots.get(rootName);
		File file;
		if (root != null)
			if (end == -1)
				file = root;
			else
				file = new File(root, path.substring(end+1));

		root = projectRoots.get(null);
		if (root != null)
			file = new File(root, path.substring(1));
		else
			file = new File(path);
		
		return new FileResource(path, file);
	}
	
	public FileSystemProject root(String name, String path) {
		projectRoots.put(name, new File(path).getAbsoluteFile());
		return this;
	}

	@Override
	public Iterable<Resource> allResources() {
		return new Iterable<Resource>() {
			public Iterator<Resource> iterator() {
				return new NestedIterator<Resource>(projectRoots.values()) {
					@Override
					protected boolean isBranchNode(Object object) {
						return object instanceof File && ((File)object).isDirectory();
					}
				};
			}
		};
	}
}
